package com.carboncntr.helper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.carboncntr.tables.Customer;
import com.carboncntr.tables.Order;
import com.carboncntr.util.HibernateUtil;

public class OrderHelper {
	public final Long saveOrder(BigDecimal carbonAmt,Customer customer,Date entryDate,BigDecimal price,Date lastMod){
		Session session=HibernateUtil.getSessionfactory().openSession();
		Transaction transaction=null;
		Long orderId=null;
		try {
			transaction=session.beginTransaction();
			Order order=new Order();
			
			order.setCarbonAmt(carbonAmt);
			order.setCustomer(customer);
			order.setEntryDate(entryDate);
			order.setPrice(price);
			order.setLastMod(lastMod);
			orderId=(Long) session.save(order);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		
		return orderId;
	}

	public final void listOrders() 
	{ 
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null; 
		try { 
			transaction = session.beginTransaction();           
			List orders = session.createQuery("from carb_order").list(); 

			for (Iterator iterator = orders.iterator(); iterator.hasNext();){ 
				Order order= (Order) iterator.next(); 
				System.out.println(order.getOrderId()); 
			} 
			transaction.commit(); 
		} catch (HibernateException e) { 
			transaction.rollback(); 
			e.printStackTrace(); 
		} finally { 
			session.close(); 
		} 
	}
	
	public final void updateOrder(Long orderId,BigDecimal carbonAmt,Customer customer,Date entryDate,BigDecimal price,Date lastMod) { 
		Session session = HibernateUtil.getSessionfactory().openSession();         
		Transaction transaction = null;         
		try {             
			transaction = session.beginTransaction();         
			Order order= (Order) session.get(Order.class, orderId); 
			order.setCarbonAmt(carbonAmt); 
			transaction.commit();     
		} catch (HibernateException e) {             
			transaction.rollback();        
			e.printStackTrace(); 
		} finally { 
			session.close();     
		} 
	}
	public final void deleteOrder(Long orderId){
		Session session = HibernateUtil.getSessionfactory().openSession(); 
		Transaction transaction = null; 
	        
		try {             
			transaction = session.beginTransaction();         
			Order order= (Order) session.get(Order.class, orderId); 
			session.delete(order); 
			transaction.commit();     
		} catch (HibernateException e) {             
			transaction.rollback();        
			e.printStackTrace();     
		} finally {             
			session.close(); 	    
		}     
	} 


}
